//
// Created by LiuYou on 2021/7/2.
//

#include <cstdlib>
#include <unistd.h>
#include <cstdio>
#include <pthread.h>
#include <cstring>
#include "MySemaphore.hpp"


#define LEFT            30000000
#define RIGHT           30000200
#define THR_NUM         (RIGHT - LEFT + 1)
#define N               4


static mysem_t* sem;

static void* thr_prime(void* pVoid);


int main() {

    pthread_t tid[THR_NUM];

    sem = mySemInit(N);
    if (sem == nullptr) {
        std::fprintf(stderr, "mySemInit() 失败！\n");
        std::exit(EXIT_FAILURE);

    }


    for (int i = LEFT; i <= RIGHT; ++i) {
        mySemSub(sem, 1);
        int* pInt = new int(i);
        int err = pthread_create(tid + (i - LEFT), nullptr, thr_prime, pInt);
        if (err) {
            std::fprintf(stderr, "pthread_create(): %s\n", std::strerror(err));
            std::exit(1);
        }
    }
    for (int i = LEFT; i <= RIGHT; ++i) {
        pthread_join(tid[i - LEFT], nullptr);
    }

    mySemDestroy(sem);

    std::exit(0);
}

static void* thr_prime(void* pVoid) {
    int mark{1};

    int i = *((int*) pVoid);
    delete (int*) pVoid;


    for (int j = 2; j < i / 2; ++j) {
        if (i % j == 0) {
            mark = 0;
            break;
        }
    }
    if (mark == 1) {
        std::fprintf(stdout, "%d is prime number.\n", i);
    }

    sleep(5);

    mySemAdd(sem, 1);

    pthread_exit(nullptr);
}